// Modules to control application life and create native browser window
const {app, BrowserWindow, ipcMain, Menu, Notification, Tray, dialog} = require('electron')
const path = require('path')
const DataFileStore = require('./renderer/DataFileStore')   // 自定义的文件存储class
const dataFileStore = new DataFileStore({name: 'music'}, 'files')

/**  electron-store 示例 */
// const Store = require('electron-store');
//
// const store = new Store();
// console.log('配置文件存储路径：', app.getPath('userData'));
// store.set('unicorn', '🦄');
// console.log(store.get('unicorn'));
// //=> '🦄'
//
// // Use dot-notation to access nested properties
// store.set('foo.bar', true);
// console.log(store.get('foo'));
// //=> {bar: true}
//
// store.delete('unicorn');
// console.log(store.get('unicorn'));
// //=> undefined

/**  系统通知 node-notifier 方式，图标怪怪的 */
// const { WindowsBalloon } = require('node-notifier');
//
// const notifier = new WindowsBalloon({
//   withFallback: false, // Try Windows Toast and Growl first?
//   customPath: void 0 // Relative/Absolute path if you want to use your fork of notifu
// });
//
// notifier.notify({
//   title: 'My notification',
//   message: 'Hello, there!',
//   sound: true, // true | false.
//   time: 5000, // How long to show balloon in ms
//   wait: false, // Wait for User Action against Notification
//   type: 'info' // The notification type : info | warn | error
// }, function(error, response) {
//   console.log(response);
// });

let mainWindow, isExit = false

/**
 * Skill.06 定义创建窗口的class
 */
class AppWindow extends BrowserWindow {
  constructor(config, pageLocation) {
    const baseConfig = {
      width: 800,
      height: 600,
      show: false,
      webPreferences: {
        // nodeAPI支持
        nodeIntegration: true
      }
    }
    // const finalConfig = Object.assign(baseConfig, config)
    const finalConfig = { ...baseConfig, ...config}
    super(finalConfig)
    this.loadFile(pageLocation)
    this.once('ready-to-show', () => {
      this.show()
    })
  }

}

function createWindow() {
  // Skill.03 >>>  隐藏菜单栏 start   注意引入electron的Menu模块
  Menu.setApplicationMenu(null)
  // .03  隐藏菜单栏 end

  // 原始方法创建窗口
  // mainWindow = new BrowserWindow({
  //   width: 800,
  //   height: 600,
  //   webPreferences: {
  //     preload: path.join(__dirname, 'preload.js')
  //   }
  // })
  // mainWindow.loadFile('index.html')

  // 使用自定义的AppWindow创建窗口
  mainWindow = new AppWindow({
    webPreferences:{
      nodeIntegration: true,
      preload: path.join(__dirname, 'preload.js')
    }

  }, 'index.html')


  // Open the DevTools.
  mainWindow.webContents.openDevTools()

  // Skill.01 >>>  创建窗口 start
  // const secondWindow = new AppWindow({
  //   width: 400,
  //   height: 300,
  //   // 指定从属关系
  //   parent: mainWindow,
  //   // 无边框窗口，不带外壳（包括窗口边框、工具栏等）
  //   frame: false,
  //   // 透明窗口
  //   // transparent: true,
  // }, 'second.html')
  // .01 创建窗口 end


  // Emitted when the window is closed.
  // mainWindow.on('closed', function () {
  //   // Dereference the window object, usually you would store windows
  //   // in an array if your app supports multi windows, this is the time
  //   // when you should delete the corresponding element.
  //   mainWindow = null
  // })




  // Skill.05 >>>  系统托盘 Tray start
  let tray = null

  //系统托盘右键菜单
  let trayMenuTemplate = [{
    label: '设置', click: function () {
      //打开相应页面
      app.open('render/index.html')
    }
  }, {
    label: '帮助', click: function () {
    }
  }, {
    label: '关于', click: function () {
    }
  }, {
    label: '退出', click: function () {
      //ipc.send('close-main-window');
      // console.log('click quit!')
      isExit = true
      app.quit();
    }
  }];

  // app.on('ready', () => {
  tray = new Tray('images/app.ico')
  // 图标的上下文菜单
  const contextMenu = Menu.buildFromTemplate(trayMenuTemplate)
  // 设置鼠标悬停的展示文本
  tray.setToolTip('This is Mine App~')
  // 设置此图标的上下文菜单
  tray.setContextMenu(contextMenu)
  tray.on('click', () => {
    mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
  })
  mainWindow.on('show', () => {
    tray.setHighlightMode('always')
  })
  mainWindow.on('hide', () => {
    tray.setHighlightMode('never')
  })
  // })

  // 重新定义主窗口关闭事件，让程序运行在后台1
  mainWindow.on('close', (event) => {
    if (!isExit) {
      event.preventDefault();
    }
    mainWindow.hide()
  })
  // .05  系统托盘 Tray end

}

/** >>>>>>>>>>>>>>>>>>>>>>>>> 主进程事件监听 Start <<<<<<<<<<<<<<<<<<<<<< */

// Skill.02.Com.01 >>> 进程间通信 start
ipcMain.on('message', (event, arg) => {
  console.log('ipcMain receive msg:', arg)
  mainWindow.send('reply', 'ipcMain received msg')
})
// .02.Com.01 进程间通信 end

// Skill.07 >>>  打开文件选择框 start
ipcMain.on('select-music', (event) => {
  dialog.showOpenDialog({
    properties: ['openFile', 'multiSelections'],
    filters: [{name: 'Music', extensions: ['mp3']}]
  }, (files) => {
    event.sender.send('load-music', files)
  })
})
// Skill.07 >>>  打开文件选择框 end

// Skill.08 >>>  信息持久化到文件 Electron-store  start
ipcMain.on('import-music', (event, files) => {
  let result = dataFileStore.addData(files).getData()
  console.log('文件存储结果:', result)
  event.sender.send('import-music-finish')
})
// Skill.08 >>>  信息持久化到文件 Electron-store  end

/** >>>>>>>>>>>>>>>>>>>>>>>>> 主进程事件监听 End <<<<<<<<<<<<<<<<<<<<<<< */

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) createWindow()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
